import Router from 'koa-router'
import { GET } from '../../common/Request'
import { User } from '../../service'
import CONFIG from '../../config'
const router = new Router();

router.post('/login', async(ctx)=>{
    if(ctx.request.header.user){
        return await User.get(ctx.request.header.user);
    }else if(ctx.request.body && ctx.request.body.code){
        let req = ctx.request.body
        let data = await GET(`https://api.weixin.qq.com/sns/jscode2session?appid=${CONFIG.APPID}&secret=${CONFIG.SECRET}&js_code=${req.code}&grant_type=authorization_code`)
        if(data.errcode){
            throw { errMsg : '无法获取APP Token' }
        }
        let user = {
            id : data.openid,
            session : data.session_key,
            avatarUrl : req.avatarUrl,
            nickname : req.nickName
        }
        await User.save(user)
        return await User.get(data.openid);
    }else{
        ctx.throw(404, 'Bad Request');
    }
})

router.post('/bind', async(ctx)=>{
    let user = await User.get(ctx.request.body.user);
    user.provincecode = ctx.request.body.provincecode
    user.province = ctx.request.body.province
    user.carnumber = ctx.request.body.carnumber
    user.phone = ctx.request.body.phone
    user.code = ctx.request.body.code
    user.formId = ctx.request.body.formId
    user.save()
    return user
})

router.get('/code', async(ctx)=>{
    let user = await User.getByCode(ctx.query.code)
    if(!user){
        return { }
    }else{
        user.phone = null
        return user
    }
})

router.get('/callphone', async(ctx)=>{
    let callby = await User.get(ctx.query.callby)
    if(callby.money <= 0 || callby.status == 0){//如果余额不够，或者用户已到期
        return { status : true, phone : callby.phone }
    }else{
        try{
            //扣费，然后进行电话号码隐藏
            let data = await GET(`http://www.putstore.cn:8089/axn/bind/${callby.phone}`)
            return { status : true, phone : data.toString() }
        }catch(e){
            return { status : true, phone : callby.phone }
        }
    }
})

router.post('/feedback', async(ctx)=>{
    return {}
})

router.get('/info', async(ctx)=>{
    return await User.get(ctx.query.user)
})

export default router
